package com.qdxwx.manage.controller.book;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.ImageUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.book.BookService;
import com.qdxwx.data.service.book.BookTeacherService;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.book.Book;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.teacher.Teacher;
import com.qdxwx.models.teacher.TeacherQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 书籍Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/book")
public class BookEditController extends BaseController {

    @Autowired
    private BookService bookService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BookTeacherService bookTeacherService;

    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error404;
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if (channelId < 1) return error404;
        TeacherQuery teacherQuery = new TeacherQuery();
        teacherQuery.setIsDisabled(0);
        List<Teacher> teacherList = teacherService.getList(teacherQuery, null);
        Teacher teacher = teacherService.getByMobile(manager.getMobile());
        List<Integer> teacherIds = new ArrayList<>();
        if (teacher != null){
            teacherIds.add(teacher.getId());
        }
        Book book = new Book();
        book.setChannelId(channelId);
        book.setCategoryId(0);
        book.setCategoryName("请选择分类");
        book.setPrice(0);
        book.setBinding("平装");
        book.setSourcePrice(0);
        book.setPublisher("华中科技大学出版社");
        mmap.put("book", book);
        mmap.put("teacherIds", teacherIds);
        mmap.put("teacherList", teacherList);
        return "book/book-edit";
    }

    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error404;
        Book book = bookService.get(id);
        if (book == null) return error500;
        List<Integer> teacherIds = bookTeacherService.getTeacherIds(id);
        TeacherQuery teacherQuery =  new TeacherQuery();
        teacherQuery.setIsDisabled(0);
        List<Teacher> teacherList = teacherService.getList(teacherQuery, null);
        mmap.put("book", book);
        mmap.put("teacherIds", teacherIds);
        mmap.put("teacherList", teacherList);
        return "book/book-edit";
    }

    @PostMapping("/save.json")
    @Permissions("book:edit")
    @Log(title = "编辑书籍", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult save(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if(manager == null) return error("未登录，禁止操作");
        int id = TKConvert.toInteger(request.getParameter("id"));
        Book book = new Book();
        if (id > 0) {
            book = bookService.get(id);
            if (book == null) return error("找不到id为:" + id + "的书籍");
        }
        String title = request.getParameter("title");
        if (TKString.isEmpty(title)) return error("书名不能为空");
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return error("请选择分类");
        Category category = categoryService.get(categoryId);
        if (category == null) return error("找不到指定分类");
        String publisher = request.getParameter("publisher");
        if (TKString.isEmpty(publisher)) return error("书籍出版社不能为空");
        String isbn = request.getParameter("isbn");
        if (TKString.isEmpty(isbn)) return error("ISBN书号不能为空");
        String teacherIds = request.getParameter("teacherIdArr");
        if (TKString.isEmpty(teacherIds)) return error("请至少选择一名主编");
        String intro = request.getParameter("intro");
        if (TKString.isEmpty(intro)) return error("请输入书籍简介");
        String cover = request.getParameter("cover");
        if (TKString.isEmpty(cover)) return error("请上传封面图片");
        book.setChannelId(category.getChannelId());
        book.setCourseId(TKConvert.toInteger(request.getParameter("courseId")));
        book.setTitle(title);
        book.setPublisher(publisher);
        book.setIsbn(isbn);
        book.setBinding(request.getParameter("binding"));
        book.setPages(TKConvert.toInteger(request.getParameter("pages")));
        book.setPublishDate(TKConvert.toLocalDate(request.getParameter("publishDate")));
        book.setCategoryId(category.getCategoryId());
        book.setCategoryName(category.getCategoryName());
        book.setSubjectId(category.getSubjectId());
        book.setSourcePrice(TKConvert.toBigDecimal(request.getParameter("sourcePrice")).multiply(BigDecimal.valueOf(100)).intValue());
        book.setPrice(TKConvert.toBigDecimal(request.getParameter("sourcePrice")).multiply(BigDecimal.valueOf(100)).intValue());
        book.setCover(cover);
        book.setIntro(intro);
        book.setContext(request.getParameter("context"));
        book.setIsElite(TKConvert.toInteger(request.getParameter("isElite"),0));
        book.setIsTop(TKConvert.toInteger(request.getParameter("isTop"),0));
        book.setBuyCount(TKConvert.toInteger(request.getParameter("buyCount"),0));
        book.setViewCount(TKConvert.toInteger(request.getParameter("viewCount"),0));
        //判断图片有没有修改
        if(!TKString.isEmpty(book.getCover())) {
            //原图
            String oldPath = book.getCover();
            //新图
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadCoverThumb, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                logger.info("oldPath:" + oldPath);
                logger.info("newPath:" + newPath);
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, 300, 388);
                book.setCover(newPath);
            }
        }
        int row;
        if (id > 0) {
            row = bookService.update(book);
        } else {
            book.setUserId(manager.getUserId());
            book.setUserName(manager.getManagerName());
            book.setIsAvailable(0);
            row = bookService.insert(book);
        }
        if (row > 0) {
            bookTeacherService.deleteByBookId(book.getId());
            bookTeacherService.insert(book.getId(), TKConvert.toIntList(teacherIds));
        }
        return toAjax(row);
    }

    /**
     * 上下架
     */
    @PostMapping("/update/available.json")
    @Permissions("book:edit")
    @Log(title = "修改书籍状态", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult UpdateIsAvailable(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isAvailable = TKConvert.toInteger(request.getParameter("isAvailable"),0);
        if (id < 1 || isAvailable > 1 || isAvailable < -1 ) return error("参数异常");
        Book book = bookService.get(id);
        if(book == null) return error("未找到指定id书籍，id="+id);
        book.setIsAvailable(isAvailable);
        return toAjax(bookService.update(book));
    }

    /**
     * 固顶操作
     */
    @PostMapping("/update/top.json")
    @Permissions("book:edit")
    @Log(title = "修改书籍固顶", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult top(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isTop = TKConvert.toInteger(request.getParameter("isTop"),0);
        if (id < 1 || isTop > 1 || isTop < 0 ) return error("参数异常");
        Book book = bookService.get(id);
        if(book == null) return error("未找到指定id书籍，id="+id);
        book.setIsTop(isTop);
        return toAjax(bookService.update(book));
    }

    /**
     * 推荐操作
     */
    @PostMapping("/update/elite.json")
    @Permissions("book:edit")
    @Log(title = "修改书籍推荐", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult elite(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isElite = TKConvert.toInteger(request.getParameter("isElite"),0);
        if (id < 1 || isElite > 1 || isElite < 0 ) return error("参数异常");
        Book book = bookService.get(id);
        if(book == null) return error("未找到指定id书籍，id="+id);
        book.setIsElite(isElite);
        return toAjax(bookService.update(book));
    }
}
